import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ChatClient {
	BufferedReader in;
	PrintWriter out;
	JFrame frame = new JFrame("Chatting Client");
	JTextField inputTextField = new JTextField(40);
	JTextArea msgArea = new JTextArea(10, 40);
	JList<String> chatterList = new JList<String>();
	JLabel userName = new JLabel();
	JCheckBox whisperCheckBox = new JCheckBox();
	DefaultListModel<String> model = new DefaultListModel<String>();
	String whisperTarget = "";
	String name;
	JScrollPane txtAreaScrollPane ;

	public ChatClient() {
		initComponent();
	}

	private void initComponent() {
		inputTextField.setEditable(false);
		msgArea.setEditable(false);
		JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		whisperCheckBox.setText("귓속말");
		northPanel.add(userName);
		northPanel.add(whisperCheckBox);
		frame.getContentPane().add(northPanel, BorderLayout.NORTH);
		frame.getContentPane().add(inputTextField, BorderLayout.SOUTH);
		txtAreaScrollPane =new JScrollPane(msgArea);
		frame.getContentPane().add(txtAreaScrollPane, BorderLayout.CENTER);
		frame.getContentPane().add(new JScrollPane(chatterList),
				BorderLayout.EAST);
		chatterList.setModel(model);
		chatterList.addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent paramListSelectionEvent) {
				whisperTarget = chatterList.getSelectedValue();
			}
		});
		
		frame.pack();

		inputTextField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(whisperCheckBox.isSelected() && !whisperTarget.equals("")){
					out.println(ChatServer.WHISPER + "," +  whisperTarget + "," + name + "," + inputTextField.getText());
				}else{
					out.println(inputTextField.getText());
				}
				inputTextField.setText("");
			}
		});
	}

	private String getServerAddress() {
		return JOptionPane.showInputDialog(frame, "IP 주소를 입력하세요:", "주소 구다사이",
				JOptionPane.QUESTION_MESSAGE);
	}

	private String getName() {
		String name = JOptionPane.showInputDialog(frame, "이름을 입력하세요:", "이름을 입력하세요", JOptionPane.PLAIN_MESSAGE);
		setName(name);
		return name;
	}

	private void setName(String name) {
		this.name = name;
	}

	private void run() throws IOException {
		String serverAddress = "localhost";
		Socket socket = new Socket(serverAddress, 2828);
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		out = new PrintWriter(socket.getOutputStream(), true);

		while (true) {
			String line = in.readLine();
			System.out.println("line : " + line);
			if (line.startsWith(ChatServer.CHATTER_LIST)) {
				System.out.println("chatter : " + line);
				model.clear();
				Vector<String> parseMsg = parseMsg(line.substring(11));
				for (String string : parseMsg) {
					model.addElement(string);
				}
			}
			
			if (line.startsWith(ChatServer.NAME)) {
				out.println(getName());
				userName.setText(name);
			} else if (line.startsWith(ChatServer.NAME_UNIQUE)) {
				inputTextField.setEditable(true);
			} else if (line.startsWith(ChatServer.MESSAGE)) {
				msgArea.append(line.substring(8) + "\n");
			} else if (line.startsWith(ChatServer.WHISPER)) {
				msgArea.append(line.substring(8) + "\n");
			}
			txtAreaScrollPane.getVerticalScrollBar().setValue(txtAreaScrollPane.getVerticalScrollBar().getMaximum());
		}
	}

	private Vector<String> parseMsg(String msg) {
		msg = msg.replace("[", "");
		msg = msg.replace("]", "");

		String[] split = msg.split(",");

		Vector<String> v = new Vector<String>();

		for (String string : split) {
			v.addElement(string.trim());
		}

		return v;
	}

	public static void main(String[] args) throws Exception {
		ChatClient client = new ChatClient();
		client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		client.frame.setVisible(true);
		client.run();
	}
}